
// global variables
var acListTotal   =  0;
var acListCurrent = -1;
var acDelay		  = 400;

var acResultsId	  = "results";
var acSearchField = null;
var acResultsDiv  = null;
var acSearchField_Code	=	null;
var acURL		  	= new Array();

function searchfield(id, url, column, filter_id, code_id){
	this.id			=	id;
	this.url		=	url;
	this.codeId		=	code_id;
	this.column		=	column;
	this.filter_id	=	filter_id;
}
var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		ENTER: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8,
		ALT: 18,
		SHIFT: 16,
		LEFT: 37,
		RIGHT: 39,
		CAPSLOCK: 20
};
var acHttpRequest =	null;

function setAutoComplete(field_id, get_url){
	// Create result div if not exist
	if($("#" + acResultsId).length > 0 ){}
	else{
		$("body").append('<div id="' + acResultsId + '"></div>');
	}
	
	if(acResultsDiv==null){
		acResultsDiv	=	$("#" + acResultsId);
	}
	
	// Save the requesting url of the search field
	var search	=	new searchfield(field_id,get_url);
	acURL.push(search);

	//Blur listener
	$("#" + field_id).blur(function(){;setTimeout("clearAutoComplete()", 400) });

	// Key up listener
	$("#" + field_id).keyup(function (e) {

		// Get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = $(this).val();
		
		// Check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}
		
		if(keyCode == KEY.LEFT || keyCode == KEY.RIGHT || keyCode == KEY.CAPSLOCK){
			return;
		}
		
		// Check for an ENTER or ESC or TAB
		if(keyCode == KEY.ENTER || keyCode == KEY.ESC || keyCode == KEY.TAB
			||keyCode == KEY.SHIFT || keyCode == KEY.ALT){
			clearAutoComplete();
			return;
		}
		
		// If is text, call with delay
		setTimeout(function () {autoComplete(field_id,lastVal)}, acDelay);
	});
}

// treat the auto-complete action (delayed function)
function autoComplete(field_id,lastValue)
{
	if(acHttpRequest!=null){
		acHttpRequest.abort();
	}
	// Set current search field
	acSearchField	=	$("#" + field_id);
		
	// Get the field value
	var part = acSearchField.val();

	// If it's empty clear the resuts box and return
	if(part == null || part == ''){
		clearAutoComplete();
		return;
	}

	// If it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}

	// Get the request url of the search fiels
	var url	=	null;
	for(var i=0; i<acURL.length; i++){
		if(acURL[i].id==field_id){
			url	=	acURL[i].url;
			break;
		}
	}
	
	// Reposition result div
	repositionResultsDiv();
	
	// get remote data as JSON
	acHttpRequest = $.getJSON(url + part, function(json){
		
		// get the total of results
		var ansLength = acListTotal = json.length;

		// if there are results populate the results div
		if(ansLength > 0){

			var newData = '';

			// create a div for each result
			for(i=0; i < ansLength; i++) {
				newData += '<div class="unselected">' + json[i] + '</div>';
			}

			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $("#" + acResultsId + " > div");
			
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			})
		
			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField.val(this.childNodes[0].nodeValue);
				clearAutoComplete();
			});

		} else {
			clearAutoComplete();
		}
	});
}

// clear auto complete box
function clearAutoComplete()
{
	acResultsDiv.html('');
	acResultsDiv.css("display","none");
	if(acHttpRequest!=null){
		acHttpRequest.abort();
	}
}

// reposition the results div accordingly to the search field
function repositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();
	
	// apply the css styles - optimized for Firefox
	acResultsDiv.css("position","absolute");
	acResultsDiv.css("left", sf_left);
	acResultsDiv.css("top", sf_top + sf_height + 5);
	acResultsDiv.css("width", sf_width + 4);
	acResultsDiv.css("z-index",10001);
}

// reposition the results div accordingly to the search field
function jqModalRepositionResultsDiv()
{
	// get the field position
	var sf_pos    = acSearchField.offset();
	var sf_top    = sf_pos.top;
	var sf_left   = sf_pos.left;

	// get the field size
	var sf_height = acSearchField.height();
	var sf_width  = acSearchField.width();
	
	// apply the css styles - optimized for Firefox
	acResultsDiv.css("position","fixed");
	acResultsDiv.css("left", sf_left);
	acResultsDiv.css("top", sf_top + sf_height + 5);
	acResultsDiv.css("width", sf_width + 4);
	acResultsDiv.css("z-index",10001);
}

// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
	if(keyCode == KEY.UP || keyCode == KEY.DOWN){

		if(keyCode == KEY.UP){ // keyUp
			if(acListCurrent == 0 || acListCurrent == -1){
				acListCurrent = acListTotal-1;
			}else{
				acListCurrent--;
			}
		} else { // keyDown
			if(acListCurrent == acListTotal-1){
				acListCurrent = 0;
			}else {
				acListCurrent++;
			}
		}

		// loop through each result div applying the correct style
		acResultsDiv.children().each(function(i){
			if(i == acListCurrent){
				acSearchField.val(this.childNodes[0].nodeValue);
				if(acSearchField_Code && acSearchField_Code.length > 0){
					acSearchField_Code.val(this.id);
				}
				this.className = "selected";
			} else {
				this.className = "unselected";
			}
		});

		return true;
	} else {
		// reset
		acListCurrent = -1;
		return false;
	}
}

function setAutoComplete2(field_id, get_url, filter_by_column, filter_id, code_id){
	// Create result div if not exist
	if($("#" + acResultsId).length > 0 ){}
	else{
		$("body").append('<div id="' + acResultsId + '"></div>');
	}
	
	if(acResultsDiv==null){
		acResultsDiv	=	$("#" + acResultsId);
	}
	
	var search	=	new searchfield(field_id, get_url, filter_by_column, filter_id, code_id);
	acURL.push(search);
	
	//Blur listener
	$("#" + field_id).blur(function(){
		setTimeout("clearAutoComplete()", 400); 
	});
	
	// Key up listener
	$("#" + field_id).keyup(function (e) {

		// Get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = $(this).val();
		
		// Check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}
		
		if(keyCode == KEY.LEFT || keyCode == KEY.RIGHT || keyCode == KEY.CAPSLOCK){
			return;
		}
		// Check for an ENTER or ESC or TAB
		if(keyCode == KEY.ENTER || keyCode == KEY.ESC || keyCode == KEY.TAB
			||keyCode == KEY.SHIFT || keyCode == KEY.ALT){
			clearAutoComplete();
			return;
		}
		
		// If is text, call with delay
		setTimeout(function () {autoComplete2(field_id,lastVal)}, acDelay);
	});
}

function setAutoCompleteWithjqModal(field_id, get_url, filter_by_column, filter_id, code_id){
	// Create result div if not exist
	if($("#" + acResultsId).length > 0 ){}
	else{
		$("body").append('<div id="' + acResultsId + '"></div>');
	}
	
	if(acResultsDiv==null){
		acResultsDiv	=	$("#" + acResultsId);
	}
	
	var search	=	new searchfield(field_id, get_url, filter_by_column, filter_id, code_id);
	acURL.push(search);
	
	//Blur listener
	$("#" + field_id).blur(function(){
		setTimeout("clearAutoComplete()", 400); 
	});
	
	// Key up listener
	$("#" + field_id).keyup(function (e) {

		// Get keyCode (window.event is for IE)
		var keyCode = e.keyCode || window.event.keyCode;
		var lastVal = $(this).val();
		
		// Check an treat up and down arrows
		if(updownArrow(keyCode)){
			return;
		}
		
		if(keyCode == KEY.LEFT || keyCode == KEY.RIGHT || keyCode == KEY.CAPSLOCK){
			return;
		}
		// Check for an ENTER or ESC or TAB
		if(keyCode == KEY.ENTER || keyCode == KEY.ESC || keyCode == KEY.TAB
			||keyCode == KEY.SHIFT || keyCode == KEY.ALT){
			clearAutoComplete();
			return;
		}
		
		// If is text, call with delay
		setTimeout(function () {autoComplete2(field_id,lastVal,true)}, acDelay);
	});
}

// treat the auto-complete action (delayed function)
function autoComplete2(field_id,lastValue, jqModal)
{
	if(acHttpRequest!=null){
		acHttpRequest.abort();
	}
	
	// Set current search field
	acSearchField	=	$("#" + field_id);
		
	// Get the field value
	var part = acSearchField.val();

	// If it's empty clear the resuts box and return
	if(part == null || part == ''){
		clearAutoComplete();
		return;
	}

	// If it's equal the value from the time of the call, allow
	if(lastValue != part){
		return;
	}

	// Get the request url of the search fiels
	var url	=	null;
	var getCode	=	false;
	for(var i=0; i<acURL.length; i++){
		if(acURL[i].id==field_id){
			url	=	acURL[i].url + part;
			if(acURL[i].column != undefined){
				url	= url +"& column=" + acURL[i].column;
			}
			var filter=$("#" + acURL[i].filter_id).val();
			if(filter != null){
				url	=	url + "& filter=" + filter;
			}
			if(acURL[i].codeId != undefined){
				acSearchField_Code	=	$("#" + acURL[i].codeId);
				getCode	=	true;
			}
			break;
		}
	}
	
	// Reposition result div
	if(jqModal){
		jqModalRepositionResultsDiv();
	}
	else{
		repositionResultsDiv();
	}
	
	// get remote data as JSON
	acHttpRequest = $.getJSON(url, function(json){
		
		// get the total of results
		var ansLength = acListTotal = json.length;

		// if there are results populate the results div
		if(ansLength > 0){

			var newData = '';

			// create a div for each result
			if(getCode){
				for(i=0; i < ansLength; i++) {
					newData += '<div id="' + json[i]['code'] + '" class="unselected">' + json[i]['value'] + '</div>';
				}
			}
			else{
				for(i=0; i < ansLength; i++) {
					newData += '<div class="unselected">' + json[i] + '</div>';
				}
			}

			// update the results div
			acResultsDiv.html(newData);
			acResultsDiv.css("display","block");
			
			// for all divs in results
			var divs = $("#" + acResultsId + " > div");
			
			// on mouse over clean previous selected and set a new one
			divs.mouseover( function() {
				divs.each(function(){ this.className = "unselected"; });
				this.className = "selected";
			})
		
			// on click copy the result text to the search field and hide
			divs.click( function() {
				acSearchField.val(this.childNodes[0].nodeValue);
				if(acSearchField_Code && acSearchField_Code.length > 0){
					acSearchField_Code.val(this.id);
				}
				clearAutoComplete();
			});

		} else {
			clearAutoComplete();
		}
	});
}